﻿using System;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;

namespace LOS.Redirects
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //## Get the alias that is needed to redirect to the new URL
            string strSiteName = GetSiteName();

            //## Add in other aliases here if you want to create exceptions so you can view this page without hitting the redirection code.
            if (strSiteName == "localhost")
            {
                return;
            }

            //## Create the SQL query
            string strSqlQuery = "SELECT url FROM Redirects WHERE name = '" + strSiteName + "'";

            //## Get the SQL connection string from web.config
            SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString);

            try
            {                
                using (SqlCommand sqlCmd = new SqlCommand())
                {
                    //## Set the connection and query for the SQL command
                    sqlCmd.Connection = sqlConn;
                    sqlCmd.CommandText = strSqlQuery;

                    //## Open the SQL connection
                    sqlConn.Open();

                    //## Execute the query to check if there are any records.
                    if (sqlCmd.ExecuteReader().HasRows)
                    {
                        //## Close the SQL connection, which closes the SQL command Reader. This will let us re-use the SQL command below with a Scalar.
                        sqlConn.Close();

                        //## Open the SQL connection
                        sqlConn.Open();
                        //## Get the new URL from the database and clean it.
                        string strRedirect = CleanUrl(sqlCmd.ExecuteScalar().ToString());

                        //## Close the SQL connection
                        sqlConn.Close();

                        if (Request.QueryString["aspxerrorpath"] != null)
                        {
                            //## If the user entered in a subpath, the below querystring will capture it so we append it to the URL from the DB.
                            //## Note: Must have CustomErrors turned on, and the 404 path set to /default.aspx in the web.config
                            Response.Redirect(strRedirect + Request.QueryString["aspxerrorpath"], false);
                        }
                        else
                        {
                            Response.Redirect(strRedirect, false);
                        }
                    }
                    else
                    {
                        //## Close the SQL connection
                        sqlConn.Close();

                        Response.Write("The redirect for " + strSiteName + " does not exist in the database.");
                    }

                    

                    
                }
            }
            catch (SqlException)
            {
                Response.Write("The redirect for " + strSiteName + " does not exist in the database.");
            }
            catch (Exception ex)
            {
                Response.Write("<b><font color='red'>Error: " + ex.Message + "</font></b><br /><br />");
            }
        }

        protected string GetSiteName()
        {
            string strSiteName = Request.ServerVariables["SERVER_NAME"];

            if (strSiteName.Contains("." + ConfigurationManager.AppSettings["domain"]))
            {
                //## Remove domain name. Example: ".landofsharepoint.com"
                return strSiteName.Substring(0, strSiteName.IndexOf("." + ConfigurationManager.AppSettings["domain"]));
            }

            return strSiteName;
        }

        protected string CleanUrl(string URL)
        {
            string strCleanedUrl = URL;

            if (URL.ToLower().Contains("/default.aspx"))
            {
                //## Remove "/default.aspx"
                strCleanedUrl = URL.Substring(0, URL.ToLower().IndexOf("/default.aspx"));
            }

            if (URL.IndexOf("/", URL.Length - 1) > -1)
            {
                //## Remove "/"
                strCleanedUrl = URL.Substring(0, URL.LastIndexOf("/"));
            }

            return strCleanedUrl;
        }
    }
}
